import {createRouter, createWebHistory} from 'vue-router'
import {getToken} from '@/utils/auth'

const routes = [{
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue')
}, {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
}, {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
}, {
    path: '/profile',
    name: 'Profile',
    component: () => import('../views/Profile.vue'),
    meta: {
        requiresAuth: true
    }
}, {
    path: '/flight-search',
    name: 'FlightSearch',
    component: () => import('../views/FlightSearch.vue')
}]

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    const hasToken = getToken()

    // 只处理需要登录的页面
    if (to.meta.requiresAuth && !hasToken) {
        next('/login')
    } else {
        next()
    }
})

export default router